<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2007 by CPG-Nuke Dev Team
  http://dragonflycms.org

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version

  Original copyright : (C) 2001 The phpBB Group
**********************************************/
if (!defined('CPG_NUKE')) { exit; }

require_once('modules/'.$module_name.'/init.inc');

$confirm = $_POST->txt('confirm');
$delete	 = $_POST->txt('delete');
$save = $_POST->txt('save');
$mark_list = !empty($_POST['mark']) ? $_POST['mark'] : 0;
$start = (int) $_GET->uint('start');

if ($mode == 'newpm') {
	// PM popup
	if (is_user()) {
		if ($userinfo['user_new_privmsg']) {
			$l_new_message = ( $userinfo['user_new_privmsg'] == 1 ) ? $LNG['You_new_pm'] : $LNG['You_new_pms'];
		} else {
			$l_new_message = $LNG['You_no_new_pm'];
		}
		$l_new_message .= '<br /><br />'.sprintf($LNG['Click_view_privmsg'], '<a href="'.URL::index('Private_Messages&amp;folder=inbox').'" onclick="jump_to_inbox();return false;" target="_blank">', '</a>');
	} else {
		$l_new_message = $LNG['Login_check_pm'];
	}
	$template->assign_vars(array(
		'L_CLOSE_WINDOW' => $LNG['Close_window'],
		'L_MESSAGE' => $l_new_message)
	);
	$template->set_handle('body', 'private_msgs/popup.html');
	$template->display('body');
	return;
} else if ( $mode == 'read' ) {
	require_once('modules/'.$module_name.'/read.php');
	return;
} else if ($delete && $mark_list) {
	require_once('modules/'.$module_name.'/delete.php');
	return;
} else if ($save && $mark_list && ($folder == 'inbox' || $folder == 'sentbox')) {
	require_once('modules/'.$module_name.'/save.php');
	return;
}

Dragonfly_Page::setTitle($folder_title);

$db->sql_query("UPDATE ".$user_prefix."_users
	SET user_unread_privmsg = user_unread_privmsg + user_new_privmsg, user_new_privmsg = 0, user_last_privmsg = ".$CPG_SESS['session_start']."
	WHERE user_id = ".$userinfo['user_id']);

$db->sql_query("UPDATE ".$prefix."_privmsgs
	SET privmsgs_type = ".PM_UNREAD_MAIL."
	WHERE privmsgs_type = ".PM_NEW_MAIL."
		AND privmsgs_to_userid = ".$userinfo['user_id']);

# Reset PM counters
$userinfo['user_new_privmsg'] = 0;
$userinfo['user_unread_privmsg'] = ($userinfo['user_new_privmsg'] + $userinfo['user_unread_privmsg']);


require_once('header.php');

# General SQL to obtain messages
$sql_tot = "SELECT COUNT(privmsgs_id) AS total FROM ".$prefix."_privmsgs ";
$sql = "SELECT pm.privmsgs_type, pm.privmsgs_id, pm.privmsgs_date, pm.privmsgs_subject, u.user_id, u.username
	FROM ".$prefix."_privmsgs pm, ".$user_prefix."_users u ";
switch ($folder)
{
	case 'inbox':
		$sql_tot .= 'WHERE privmsgs_to_userid = '.$userinfo['user_id'].'
			AND ( privmsgs_type =  '.PM_NEW_MAIL.'
				OR privmsgs_type = '.PM_READ_MAIL.'
				OR privmsgs_type = '.PM_UNREAD_MAIL.' )';

		$sql .= 'WHERE pm.privmsgs_to_userid = '.$userinfo['user_id'].'
			AND u.user_id = pm.privmsgs_from_userid
			AND ( pm.privmsgs_type =  '.PM_NEW_MAIL.'
				OR pm.privmsgs_type = '.PM_READ_MAIL.'
				OR privmsgs_type = '.PM_UNREAD_MAIL.' )';
		break;

	case 'outbox':
		$sql_tot .= 'WHERE privmsgs_from_userid = '.$userinfo['user_id'].'
			AND ( privmsgs_type =  '.PM_NEW_MAIL.'
				OR privmsgs_type = '.PM_UNREAD_MAIL.' )';

		$sql .= 'WHERE pm.privmsgs_from_userid = '.$userinfo['user_id'].'
			AND u.user_id = pm.privmsgs_to_userid
			AND ( pm.privmsgs_type =  '.PM_NEW_MAIL.'
				OR privmsgs_type = '.PM_UNREAD_MAIL.' )';
		break;

	case 'sentbox':
		$sql_tot .= 'WHERE privmsgs_from_userid = '.$userinfo['user_id'].'
			AND privmsgs_type =	 '.PM_SENT_MAIL;

		$sql .= 'WHERE pm.privmsgs_from_userid = '.$userinfo['user_id'].'
			AND u.user_id = pm.privmsgs_to_userid
			AND pm.privmsgs_type =	'.PM_SENT_MAIL;
		break;

	case 'savebox':
		$sql_tot .= 'WHERE ( ( privmsgs_to_userid = '.$userinfo['user_id'].'
				AND privmsgs_type = '.PM_SAVED_IN_MAIL.' )
			OR ( privmsgs_from_userid = '.$userinfo['user_id'].'
				AND privmsgs_type = '.PM_SAVED_OUT_MAIL.') )';

		$sql .= 'WHERE u.user_id = pm.privmsgs_from_userid
			AND ( ( pm.privmsgs_to_userid = '.$userinfo['user_id'].'
				AND pm.privmsgs_type = '.PM_SAVED_IN_MAIL.' )
			OR ( pm.privmsgs_from_userid = '.$userinfo['user_id'].'
				AND pm.privmsgs_type = '.PM_SAVED_OUT_MAIL.' ) )';
		break;

	default:
		cpg_error($LNG['No_such_folder']);
		break;
}

# Show messages over previous x days/months
$limit_msg_time_total = $limit_msg_time = '';

if ($msg_days = $_POST->uint('msgdays')) {
	$min_msg_time = time() - ($msg_days * 86400);

	$limit_msg_time_total = " AND privmsgs_date > $min_msg_time";
	$limit_msg_time = " AND pm.privmsgs_date > $min_msg_time ";

	//if (!empty($_POST['msgdays'])) {
		//$start = 0;
	//}
}

$orders_by = array(
	'time' => 'pm.privmsgs_date',
	'username' => 'u.username',
	'subject' => 'pm.privmsgs_subject'
);
$order_by = isset($orders_by[$_POST->txt('order_by')]) ? $orders_by[$_POST->txt('order_by')] : $orders_by['time'];
$sql .= "{$limit_msg_time} ORDER BY {$order_by} ".('asc'===$_POST->txt('asc_desc')?'ASC':'DESC');
$sql .= " LIMIT {$MAIN_CFG[$Module->name]['per_page']} OFFSET {$start}";

$sql_all_tot = $sql_tot;
$sql_tot .= $limit_msg_time_total;

$result = $db->sql_query($sql_tot);
$pm_total = ($row = $db->sql_fetchrow($result)) ? $row['total'] : 0;
$result->free();

$result = $db->sql_query($sql_all_tot);
$pm_all_total = ($row = $db->sql_fetchrow($result)) ? $row['total'] : 0;
$result->free();


$limit = $MAIN_CFG->{$Module->name}->{$folder.'_max'};
$template->folder = array(
	'name' => $folder,
	'max' => $limit,
	'total_pms' => $pm_all_total,
	'quota' => sprintf($LNG[$folder.'_size'], 0 < $limit ? round(($pm_all_total/$limit)*100) : 100),
);


$template->listrow = array();
$result = $db->query($sql);

if ($result->num_rows) {

	$template->msgdays = select_box(
		'msgdays',
		$msg_days,
		array(
			'0' => $LNG['All_Messages'],
			'1' => $LNG['1_Day'],
			'7' => $LNG['7_Days'],
			'14' => $LNG['2_Weeks'],
			'30' => $LNG['1_Month'],
			'90' => $LNG['3_Months'],
			'180' => $LNG['6_Months'],
			'364' => $LNG['1_Year']
		)
	);

	$template->order_by = select_box(
		'order_by',
		array_search($order_by, $orders_by),
		array(
			'time' => $LNG['Order_by_time'],
			'username' => $LNG['Order_by_username'],
			'subject' => $LNG['Order_by_subject']
		)
	);

	$template->asc_desc = select_box(
		'asc_desc',
		'asc' === $_POST->txt('asc_desc') ? 'asc' : 'desc',
		array(
			'asc' => $LNG['Asc'],
			'desc' => $LNG['Desc']
		)
	);

	while ($row = $result->fetch_assoc()) {
		$template->listrow[] = array(
			'FROM' => $row['username'],
			'SUBJECT' => $row['privmsgs_subject'],

			'DATE' => L10NTime::date($userinfo->dateformat, $row['privmsgs_date']),
			'PM_NEW_MAIL' => ($row['privmsgs_type'] == PM_UNREAD_MAIL),
			'MSG_ID' => $row['privmsgs_id'],

			'U_READ' => URL::index('&amp;folder='.$folder.'&amp;mode=read&amp;p='.$row['privmsgs_id']),
			'U_FROM_USER_PROFILE' => URL::index('Your_Account&amp;profile='.$row['user_id']),
		);
	}
	$template->pm_pagination = pm_pagination("{$Module->name}&amp;folder={$folder}", $pm_total, $MAIN_CFG->{$Module->name}->per_page, $start);
}
$result->free();

$template->display('Private_Messages/index');
